﻿#region Disclaimer / License
// Copyright (C) 2011, Kenneth Bergeron, IAP Worldwide Services, Inc
// NOAA :: National Marine Fisheries Service
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataSets
{
    /// <summary>
    /// Post the local XML database to the SDES Access database
    /// </summary>
    public static class PostFish
    {
        /// <summary>
        /// Get the SDES station number given VesselCode, Cruise and other kind of station number
        /// </summary>
        /// <param name="aVesselCode">Vessel ID</param>
        /// <param name="aCruise">Cruise number</param>
        /// <param name="aStationNumber">Station number</param>
        /// <returns></returns>
        private static Int32 StationNumber(string aVesselCode, string aCruise, string aStationNumber)
        {
            // What was that mod 10 stuff all about???
            //int VesselCode = 0;
            //if(!int.TryParse(aVessel, out VesselCode)) return -1;
            int Result = 0;
            // ??? if (!int.TryParse((VesselCode % 10).ToString() + aCruise + aStationNumber, out Result)) return -1;
            // Now, I guess, just cat together and return as a int32
            if (!int.TryParse(aVesselCode + aCruise + aStationNumber, out Result)) return -1;
            return Result;
        }
        /// <summary>
        /// Post the local XML database to the SDES Access database
        /// </summary>
        public static bool Post(string aVesselCode, string aCruise,
            LocalDataSet aLocalDataSet, EASADataSet aEASADataSet,
            System.ComponentModel.ProgressChangedEventHandler aProgress)
        {
            // Make a fake stationKey to check vessel and cruise
            int StationKey = StationNumber(aVesselCode, aCruise, "000");
            if (StationKey == -1)
            {
                // MessageBox.Show("Vessel number or Cruise ID is not valid; correct with Setup.");
                return false;
            }
            double Entries = aLocalDataSet.Fish.Count;
            double Count = 0d;
            foreach (DataSets.LocalDataSet.FishRow fRow in aLocalDataSet.Fish)
            {
                // Get the event id
                StationKey = StationNumber(aVesselCode, aCruise, fRow.Station);
                if (StationKey == -1)
                {
                    fRow.SetColumnError(aLocalDataSet.Fish.StationColumn, "Station number is not valid");
                    return false;
                }
                DataSets.EASADataSet.eventsRow[] eRows = aEASADataSet.events.Select(
                    "STATIONKEY = " + StationKey.ToString())
                    as DataSets.EASADataSet.eventsRow[];
                if (eRows == null || eRows.Length == 0)
                {
                    //fRow.SetColumnError(aLocalDataSet.Fish.StationColumn, "Station number is not in events table");
                    // return false;
                    DataSets.EASADataSet.stationsRow sRow = aEASADataSet.stations.FindBySTATIONKEY(StationKey);
                    if (sRow == null) sRow = aEASADataSet.stations.AddstationsRow(
                        StationKey,
                        aVesselCode,
                        aCruise,
                        fRow.Station,
                        "HUH",
                        DateTime.Now,
                        (short)DateTime.Now.Year);
                    eRows = new DataSets.EASADataSet.eventsRow[] 
                    {
                        aEASADataSet.events.AddeventsRow(sRow, "Catch", fRow.Station, 0d, 0d, 0d, 0d)
                    };

                }
                // Look in catch table
                string fWeight = fRow.WeightEstimated ? "E" : string.Empty;
                int TRSN = int.Parse(fRow.TRSN);
                var Query = from DataSets.EASADataSet.catchRow qRow in aEASADataSet._catch
                            where !qRow.IsTRSNNull() && qRow.TRSN == TRSN && !qRow.IsWTCODENull() && qRow.WTCODE == fWeight
                            select qRow;
                DataSets.EASADataSet.catchRow cRow = null;
                if (Query.Count() == 0)
                    cRow = aEASADataSet._catch.AddcatchRow(
                        eRows[0],
                        fRow.Species,
                        false,
                        string.Empty,
                        TRSN,
                        "N",
                        0,
                        0f,
                        0,
                        0f,
                        string.Empty,
                        false,
                        string.Empty);
                else
                    cRow = Query.First();
                cRow.NSELECT = cRow.NSELECT + 1;
                cRow.WSELECT = cRow.WSELECT + (float)fRow.Weight;
                if (!fRow.IsCommentNull() && !string.IsNullOrEmpty(fRow.Comment))
                    cRow.COMMENTS = cRow.COMMENTS + ";" + fRow.Comment;
                if (fRow.GetFishSamplesRows().Length > 0)
                    cRow.SPCTAKEN = true;
                // Add WEIGHT into the LENGTH DETAIL database ?!?!!
                DataSets.EASADataSet.lengthdetailsRow lRow =
                    aEASADataSet.lengthdetails.AddlengthdetailsRow(
                        cRow,
                        fRow.HookID.ToString(),
                        fRow.MortalityCode.StartsWith("D"),
                        (short)fRow.HookID,
                        (float)fRow.Weight,
                        fRow.WeightEstimated,
                        string.Empty,
                        fRow.SexCode,
                        fRow.StageCode,
                        0f,
                        fRow.Comment);
                // Add lengths into LengthFrequency
                if (fRow.LenTotal != 0)
                    aEASADataSet.lengthfreq.AddlengthfreqRow(
                        0,
                        lRow,
                        fRow.LengthEstimated,
                        "18",
                        (short)fRow.LenTotal);
                if (fRow.LenFork != 0)
                    aEASADataSet.lengthfreq.AddlengthfreqRow(
                        0,
                        lRow,
                        fRow.LengthEstimated,
                        "01",
                        (short)fRow.LenFork);
                if (fRow.LenStd != 0)
                    aEASADataSet.lengthfreq.AddlengthfreqRow(
                        0,
                        lRow,
                        fRow.LengthEstimated,
                        "02",
                        (short)fRow.LenStd);
                // Add the special lengths
                foreach (DataSets.LocalDataSet.FishSamplesRow sRow in fRow.GetFishSamplesRows())
                {
                    if (sRow.Sample == DataSets.LocalDataSet.FishSamplesRow.SampleType.Measurement)
                        aEASADataSet.lengthfreq.AddlengthfreqRow(
                            0,
                            lRow,
                            fRow.LengthEstimated,
                            sRow.CODE,
                            (short)sRow.Value);
                    else if (sRow.Sample == DataSets.LocalDataSet.FishSamplesRow.SampleType.Sample)
                        aEASADataSet.samples.AddsamplesRow(
                            0,
                            lRow,
                            sRow.CODE,
                            string.Empty,
                            (float)sRow.Value,
                            sRow.Description,
                            sRow.Identifier,
                            sRow.Comment);
                    else if (sRow.Sample == DataSets.LocalDataSet.FishSamplesRow.SampleType.Tag)
                        aEASADataSet.tagnumbers.AddtagnumbersRow(
                            0,
                            lRow,
                            sRow.CODE,
                            sRow.Comment,
                            !sRow.Retrieved,
                            sRow.Description);
                }
                if (aProgress != null) aProgress(null, new System.ComponentModel.ProgressChangedEventArgs(
                     (int)(Count / Entries * 100d), null));
                Count += 1d;
            }
            return true;
        }
        /// <summary>
        /// Post the SDES Access database to the local XML database
        /// </summary>
        public static bool UnPost(EASADataSet aEASADataSet, LocalDataSet aLocalDataSet)
        {
            int hid = 0;
            foreach (DataSets.EASADataSet.eventsRow eRow in aEASADataSet.events)
            {
                foreach (EASADataSet.catchRow cRow in eRow.GetcatchRows())
                {
                    LocalDataSet.FishRow FishRow = aLocalDataSet.Fish.NewFishRow();
                    FishRow.VesselCode = eRow.stationsRow.VESSEL;
                    FishRow.Cruise = eRow.stationsRow.CRUISE;
                    FishRow.HookID = hid++; // ldRow.IsCATCH_IDNull() ? 0 : ldRow.CATCH_ID;
                    //                                    012345678
                    string sk = eRow.STATIONKEY.ToString("000000000");
                    FishRow.Station = sk.Substring(6);

                    FishRow.Species = cRow.TAXON;
                    FishRow.TRSN = cRow.TRSN.ToString();
                    foreach (EASADataSet.lengthdetailsRow ldRow in cRow.GetlengthdetailsRows())
                    {
                        FishRow.Mortality = ldRow.IsDEADNull() ? LocalDataSet.FishRow.Mortalities.Dead : (ldRow.DEAD ? LocalDataSet.FishRow.Mortalities.Dead : LocalDataSet.FishRow.Mortalities.Alive);
                        FishRow.Weight = ldRow.IsINDVL_WEIGHTNull() ? 0d : ldRow.INDVL_WEIGHT;
                        FishRow.WeightEstimated = ldRow.INDVL_W_ESTIMATED;
                        FishRow.SexCode = ldRow.IsSEXNull() ? string.Empty : ldRow.SEX;
                        FishRow.StageCode = ldRow.IsMATURITYNull() ? string.Empty : ldRow.MATURITY;
                        FishRow.Comment = ldRow.IsCOMMENTSNull() ? string.Empty : ldRow.COMMENTS;
                        FishRow.LengthEstimated = false;
                        FishRow.LenTotal =
                            FishRow.LenFork =
                            FishRow.LenStd = 0d;
                        foreach (EASADataSet.lengthfreqRow lfRow in ldRow.GetlengthfreqRows())
                        {
                            FishRow.LengthEstimated = lfRow.LENGTHESTIMATED;
                            FishRow.LenTotal =
                                FishRow.LenFork = 
                                FishRow.LenStd = 0d;
                            switch (lfRow.SIZECODE)
                            {
                                case "18":
                                    FishRow.LenTotal = lfRow.SIZELENGTH;
                                    break;
                                case "01":
                                    FishRow.LenFork = lfRow.SIZELENGTH;
                                    break;
                                case "02":
                                    FishRow.LenStd = lfRow.SIZELENGTH;
                                    break;
                                default:
                                    LocalDataSet.FishSamplesRow fsRow = FishRow.NewFishSamplesRow();
                                    fsRow.Sample = DataSets.LocalDataSet.FishSamplesRow.SampleType.Measurement;
                                    fsRow.CODE = lfRow.SIZECODE;
                                    fsRow.Value = lfRow.SIZELENGTH;
                                    FishRow.AddFishSamplesRow(fsRow);
                                    break;
                            }
                        }
                        foreach (EASADataSet.samplesRow samRow in ldRow.GetsamplesRows())
                        {
                            LocalDataSet.FishSamplesRow fsRow = FishRow.NewFishSamplesRow();
                            fsRow.Sample = DataSets.LocalDataSet.FishSamplesRow.SampleType.Sample;
                            fsRow.CODE = samRow.IsSAMPLECODENull() ? string.Empty : samRow.SAMPLECODE;
                            fsRow.Description = samRow.IsSAMPLEREQUESTNull() ? string.Empty : samRow.SAMPLEREQUEST;
                            fsRow.Identifier = samRow.IsSAMPLEPURPOSENull() ? string.Empty : samRow.SAMPLEPURPOSE;
                            fsRow.Comment = samRow.IsCOMMENTSNull() ? string.Empty : samRow.COMMENTS;
                            fsRow.Value = 0d;
                            FishRow.AddFishSamplesRow(fsRow);
                        }
                        foreach (EASADataSet.tagnumbersRow tRow in ldRow.GettagnumbersRows())
                        {
                            LocalDataSet.FishSamplesRow fsRow = FishRow.NewFishSamplesRow();
                            fsRow.Sample = DataSets.LocalDataSet.FishSamplesRow.SampleType.Tag;
                            fsRow.CODE = tRow.TAGCODE;
                            fsRow.Identifier = tRow.TAGNUMBER;
                            fsRow.Retrieved = !tRow.TAGDEPLOYED;
                            fsRow.Comment = tRow.COMMENTS;
                            FishRow.AddFishSamplesRow(fsRow);
                        }
                    }
                    aLocalDataSet.Fish.AddFishRow(FishRow);
                }
            }
            return true;
        }
    }
}
